package org.dg.iag.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dg.iag.dao.GenericDAO;
import org.dg.iag.entity.ImportLogStatus;
import org.dg.iag.entity.Log;
import org.dg.iag.entity.Logs;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.query.XQueryUtil;
import org.dg.iag.server.LogsServerResource;
import org.dg.iag.server.LogsServerResource.LogsResource;

public class ImportManager {
	private static Logger logger		= Logger.getLogger(ImportManager.class);
	
	public ImportLogStatus reloadAll() {
		ImportLogStatus ils		=  ImportLogStatus.getInstance();
		if ( ils.getFinished() == null || ils.getFinished() ) {
			ils.setFinished(false);
			ils.setTotalNoTags(0);
			ils.setCurrentTagNo(0);
			ImportThread thread	= new ImportThread();
			
			if ( ImportThread.importThread != null && ImportThread.importThread.isAlive() )
				thread.stop.set(true);
			ImportThread.importThread	= thread;
			thread.start();
		}
		else {
			return ils;
		}
		return ils;
	}
	
	public ImportLogStatus reloadFailed (String logId) {
		ImportLogStatus ils		= ImportLogStatus.getInstance();
		GenericDAO<Log, Logs> gdao	= 	new GenericDAO<Log, Logs>(ApplicationConstants.LOGS_XML_FOLDER);
		ImportThread thread			= null;
		if (logId != null ){
			Log log		= gdao.getElement(LogsServerResource.LogResource.class, "/Logs/Log[id="+logId+"]");
			if ( log != null)
				thread		= new ImportThread(log.getFeedTag(), log.getTimeMillis(), false );
		}
		else { // Reload all failed
			Map<String,String> filterMap	= new HashMap<String, String>();
			XQueryGet xqg			= new XQueryGet("", "max(/Logs/Log/timeMillis)", false);
			
			String result			= gdao.getElementsAsString(xqg);
			long resultLong			= Double.valueOf(result).longValue();
			filterMap.put("timeMillis", resultLong+"");
			filterMap.put("importStatus",0+"");
			
			String query					= "let $ret := /Logs/Log" + XQueryUtil.generateXpathCondition(filterMap, true) + 
					" return <Logs>{$ret}</Logs> ";
			XQueryGet xqg2					= new XQueryGet("", query , false);
			Logs failedLogs					= gdao.getElements(LogsResource.class, xqg2);
			if ( failedLogs != null && failedLogs.getLogs() != null && failedLogs.getLogs().size() > 0 ) {
				long groupId					= failedLogs.getLogs().get(0).getTimeMillis();
				List<String> tagsList			= new ArrayList<String>(failedLogs.getLogs().size() );
				for ( Log log: failedLogs.getLogs() ) {
					tagsList.add(log.getFeedTag() );
				}
				thread							= new ImportThread(tagsList, groupId, true);
			}
		}
		
		//Initializing the thread
		if ( ImportThread.importThread != null && ImportThread.importThread.isAlive() )
			thread.stop.set(true);
		ImportThread.importThread	= thread;
		thread.start();
		return ils;
	}
	
}
